<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区开始 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数!" type="warning" :closable="false"></el-alert>
      <!-- 商品分类区域 -->
      <el-row class="cate_opt">
        <el-col>
          <span>选择商品分类：</span>

          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            @change="parentCateListChange"
            :props="cateProps"
            clearable
            change-on-select
            expand-trigger="hover"
            class="cascader"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tabs分页签切换 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加动态参数按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="isVisible=true"
          >添加动态参数</el-button>

          <!-- 动态参数表格渲染 -->
          <el-table :data="manyTabData" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
                <template slot-scope="scope">
                   <el-tag v-for="(item , i) in scope.row.attr_vals" :key="i" closable>{{item}}</el-tag>
                </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEdit(scope.row.attr_id)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeThreeId(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加静态资源按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="isVisible=true"
          >添加静态属性</el-button>
          <!-- 静态参数表格渲染 -->
          <el-table :data="onlyTabData" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
                <template slot-scope="scope">
                   <el-tag v-for="(item , i) in scope.row.attr_vals" :key="i" closable>{{item}}</el-tag>
                </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEdit(scope.row.attr_id)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeThreeId(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 卡片视图区结束 -->

    <!-- 添加参数dialog对话框开始 -->
    <el-dialog :title="'添加'+titleText" :visible.sync="isVisible" width="50%" @close="addDialogClose">

      <!-- 收集信息的form表单开始-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 收集信息的form表单结束-->

      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加参数dialog对话框结束 -->


    <!-- 修改参数dialog对话框开始 -->
    <el-dialog :title="'修改'+titleText" :visible.sync="editIsVisible" width="50%" @close="editDialogClose">

      <!-- 收集信息的form表单开始-->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 收集信息的form表单结束-->

      <span slot="footer" class="dialog-footer">
        <el-button @click="editIsVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数dialog对话框结束 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      //获取到的分类商品数据
      cateList: [],
      //级联选择框的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //级联选择框的双向数据绑定数组
      selectedKeys: [],
      activeName: 'many',
      //储存动态属性
      manyTabData: [],
      //储存静态属性
      onlyTabData: [],
      isVisible: false,
      //添加参数
      addForm:{
          attr_name:''
      },
      //添加参数的验证规则
      addFormRules:{
          attr_name:[
              { required: true, message: '请输入参数名称', trigger: 'blur' }
            
          ]
      },
      //修改对话框显示与隐藏
      editIsVisible:false,
      //修改表单数据对象
      editForm:{},
      //修改表单验证规则
      editFormRules:{
        attr_name:[
              { required: true, message: '请输入参数名称', trigger: 'blur' }
            
          ]
      },
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取分类商品数据并渲染到页面
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.cateList = res.data
      // console.log(this.cateList)
    },
    parentCateListChange() {
      this.getTabTree()
    },
    handleTabClick() {
      this.getTabTree()
    },
    //增删改查渲染的函数
    async getTabTree() {
      //   console.log(this.selectedKeys)
      //只允许选中第三级分类所以当数组长度为3时代表选中第三级了
      if (this.selectedKeys.length !== 3) {
        //没选中第三级就将数组清空然后返回
        this.selectedKeys = []
        this.manyTabData=[]
        this.onlyTabData=[]
        return
      }
      //选中第三级分类时就发起请求
      //console.log(this.selectedKeys)
      const { data: res } = await this.$http.get(
        `categories/${this.getThreeId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) return this.$message.error('获取参数失败')
  
      //对attr_vals进行分隔成数组
      res.data.forEach(item=>{
        item.attr_vals=item.attr_vals.split(',')
      })
         // console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    //监听弹出框关闭事件
    addDialogClose(){
        this.isVisible=false
        this.$refs.addFormRef.resetFields()
    },
    //点击添加事件
    addParams(){
        //进行表单域验证通过后发起请求
        this.$refs.addFormRef.validate(async valid=>{
            if(!valid) return 
            //成功后发起请求
             const {data:res} =await this.$http.post(`categories/${this.getThreeId}/attributes`,{
                 attr_name:this. addForm.attr_name,
                 attr_sel:this.activeName
             })
             if(res.meta.status!==201)  return this.$message.error('添加失败')
            // console.log(res.data)
            //重新渲染
             this.getTabTree()
                return this.$message.success('添加成功')
        })
        //重新隐藏对话框
       this.isVisible=false
    },
    //显示修改对话框
     async showEdit(attr_id){
          //发送请求获取数据
        const {data:res}= await this.$http.get(`categories/${this.getThreeId}/attributes/${attr_id}`,{params:{attr_sel:this.activeName}})
          if(res.meta.status!==200) return this.$message.error('获取数据失败')
          this.editForm=res.data
           this.editIsVisible=true
      },
      //修改对话框关闭时清空重置内容
      editDialogClose(){
         this.$refs.editFormRef.resetFields()
      },
      //点击按钮修改发送请求提交
      editParams(){
           this.$refs.editFormRef.validate(async valid=>{
               if(!valid) return  this.$message.error('请求失败')
               const {data:res}= await this.$http.put(`categories/${this.getThreeId}/attributes/${this.editForm.attr_id}`,{attr_name:this.editForm.attr_name,
                 attr_sel:this.activeName})

                 if(res.meta.status!==200){
                      return this.$message.error('修改参数失败 ')
                 }
                  //重新渲染
             this.getTabTree()  
                 this.$message.success('修改参数成功')
           })
        this.editIsVisible=false
      },
      //点击删除按钮删除参数并重新渲染页面
     async removeThreeId(attr_id){
       //提醒用户删除
            const confirmRes = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(confirmRes)点击确定返回的结果是confirm,点击取消 返回的结果是concel
      if (confirmRes !== 'confirm') {
        return this.$message.info('该操作已经取消')
       }
        //进行删除操作
         const {data:res} =await this.$http.delete(`categories/${this.getThreeId}/attributes/${attr_id}`)
         if(res.meta.status!==200) return this.$message.error('删除失败')
               //重新渲染
             this.getTabTree()  
             //提示用户成功 
                 this.$message.success('修改参数成功')
    },
  },
  //计算属性当数组长度为3时代表选择了第三级参数让按钮的disabled属性值为true否则为false
  computed: {
    isDisabled() {
      //数组长度不为3禁用
      if (this.selectedKeys.length !== 3) {
        return true
      }
      //否则开启按钮3
      return false
    },
    //获取第三级参数id
    getThreeId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cate_opt {
  margin: 15px, 0;
}
.el-card {
  margin-top: 30px;
}
.el-cascader {
  margin-top: 30px;
}
.el-tag{
  margin: 10px;
}
</style>